proc getcolor {color} {
	switch -- $color {
		0 { return white; }
		1 { return black; }
		2 { return darkblue; }
		3 { return darkgreen; }
		4 { return red; }
		5 { return darkred; }
		6 { return purple; }
		7 { return orange; }
		8 { return yellow; }
		9 { return green; }
		10 { return DeepSkyBlue; }
		11 { return aquamarine; }
		12 { return blue; }
		13 { return pink; }
		14 { return grey39; }
		15 { return darkgray; }
	}
}

proc f_output {out msg {basecolor ""}} {
	set BOLD_ON 0
	set ULINE_ON 0
	set FGCOLOR ""
	set BGCOLOR ""
	set COL1 ""
	set WAIT_FOR_COLOR 0
	set COLORVAR FGCOLOR
	
	foreach m [split $msg {}] {
		switch -- $m {
			\002 {
				if $BOLD_ON { set BOLD_ON 0; } else { set BOLD_ON 1; }
			}
			
			\037 {
				if $ULINE_ON { set ULINE_ON 0; } else { set ULINE_ON 1; }
			}
			
			\003 {
				if {($WAIT_FOR_COLOR) && ($COLORIDX < 2)} {
					set FGCOLOR ""
					set BGCOLOR ""
				}
				
				set WAIT_FOR_COLOR 1
				set COL1 ""
				set COLORIDX 0
				set COLORVAR "FGCOLOR"
			}
			
			\017 {
				set BOLD_ON 0
				set ULINE_ON 0
				set FGCOLOR ""
				set BGCOLOR ""
				set COLORVAR "FGCOLOR"
			}
			
			default {
				if {($WAIT_FOR_COLOR) && ($COLORIDX < 2)} {
					if {[string is integer $m]} {
						if { $COL1 == "" } {
							set COL1 $m
							set $COLORVAR $m
						} else {
							set $COLORVAR $COL1$m
						}
						incr COLORIDX
						continue
					} elseif {$m == ","} {
						set COLORVAR "BGCOLOR"
						set COL1 ""
						set COLORIDX 0
						continue
					} else {
						if {$COL1 == ""} {
							set FGCOLOR ""
							set BGCOLOR ""
							set WAIT_FOR_COLOR 0
						}
					}
				}
				
				if {($m == ",") && ($WAIT_FOR_COLOR) && ($COLORIDX == 2)} {
					set COLORVAR "BGCOLOR"
					set COL1 ""
					set COLORIDX 0
					continue
				}
					
				set tags ""
				if $BOLD_ON { set tags "$tags bold"; }
				if $ULINE_ON { set tags "$tags uline"; }
				if {$FGCOLOR != ""} {
					regexp {0([0-9])} $FGCOLOR -> FGCOLOR
					foreach num {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
						set color [getcolor $FGCOLOR]
						if { $FGCOLOR == $num } {
							set tags "$tags $color"
						}
					}
				}
				
				if {$BGCOLOR != ""} {
					regexp {0([0-9])} $BGCOLOR -> BGCOLOR
					foreach num {0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15} {
						set color [getcolor $BGCOLOR]
						set bg "bg"
						if { $BGCOLOR == $num } {
							set tags "$tags $color$bg"
						}
					}
				}
				
				$out insert end $m "$tags $basecolor"
			}
		}
	}
}
